/*
 * @Author: yao
 * @Date: 2024-11-12 08:57:02
 * @LastEditTime: 2024-11-19 15:03:17
 * @LastEditors: yao
 * @Description:
 * @FilePath: \jdev-web\src\router\guards.ts
 */
import router from "@/router/index";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { useUserStore } from "@/stores/modules/user";
import Config from "@/config";
import { getToken } from "@/utils/utils";
import { useAppStore } from "@/stores/modules/app";

NProgress.configure({
  showSpinner: false,
});

router.beforeEach(async (to, from, next) => {
  NProgress.start();
  const token = getToken();
  const useUser = useUserStore();
  if (token && useUser.userInfo && useUser.userInfo.userId) {
    if (!useUser.menus || useUser.menus.length <= 0) {
      const menus: any = await useUser.getResources();
      if (menus && menus.length > 0) {
        const useApp = useAppStore();
        const mData: any = await useApp.GenerateRoutes({ roles: menus });
        mData.forEach((route: any) => {
          router.addRoute(route);
        });
        next({ ...to, replace: true });
      } else {
        next();
        NProgress.done();
      }
    } else {
      next();
    }
  } else {
    if (Config.WHITE_LIST.some((n) => n === to.name)) {
      next();
    } else {
      next("/login");
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});
